package com.aerospace.utils;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ConcurrentUtils {

    private static final int COUNT = 1000;

    /**
     * 1、之前提到过的原子atomic包
     * 2、比synchronize功能更强大的lock包
     * 3、线程调度管理工具
     * 4、线程安全与并发工具集合
     * 5、线程池
     * https://www.jianshu.com/p/46728d6bc6b2
     */
    //AbstractQueuedSynchronizer
    //设置countDownlatch为100，然后在其他线程中调用100次countDown方法，随后主程序在等待100次被执行完成之后，继续执行主线程代码

    public void aqs(){
        try{
            ExecutorService executorService = Executors.newCachedThreadPool();
            //CountDownLatch
            final CountDownLatch countDownLatch = new CountDownLatch(COUNT);
            for (int i = 0; i <COUNT; i++){
                final int finalI = i;
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(3000);
                            System.out.println(finalI);
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }finally {
                            countDownLatch.countDown();
                        }
                    }
                });
            }
            countDownLatch.await(1, TimeUnit.SECONDS);
            executorService.shutdown();
            System.out.println("done!");
        }catch (Exception e){
            e.printStackTrace();
        }
    }





}

